<script setup lang="ts">
  import { computed, ref, unref, watch } from 'vue';
  import { Field, Popup, Picker } from 'vant';

  const showPopup = ref(false);

  const props = withDefaults(
    defineProps<{
      modelValue: number;
      columns: any[];
    }>(),
    {}
  );

  const tempValue = ref<number>(props.modelValue);

  const emits = defineEmits<{
    (e: 'update:modelValue', value: number): void;
  }>();

  const calcText = computed(() => () => {
    return (
      props.columns.find((item) => item.code === tempValue.value)?.text || ''
    );
  });

  /**
   * 打开picker
   */
  const handlerClick = () => {
    showPopup.value = true;
  };

  /**
   * 确定
   * @param selectedValues
   */
  const confirm = ({ selectedValues }: any) => {
    console.log(selectedValues);
    const selectDict = props.columns?.find(
      (item) => item.code === selectedValues[0]
    );
    tempValue.value = selectDict!.code;
    emits('update:modelValue', unref(tempValue));
    showPopup.value = false;
  };
</script>

<template>
  <Field
    @click="handlerClick"
    readonly
    is-link
    label="枚举选择"
    v-bind="$attrs"
    :modelValue="calcText()"
  />
  <Popup position="bottom" round v-model:show="showPopup">
    <Picker
      title="标题"
      :columns="columns"
      :modelValue="[tempValue]"
      @cancel="showPopup = false"
      @confirm="confirm"
      :columns-field-names="{
        text: 'text',
        value: 'code',
      }"
    />
  </Popup>
</template>

<style scoped lang="less"></style>
